package andy.demo.location;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
import andy.demo.R;

public class ThreeWaysGetLocation extends Activity {

	private static final String TAG = "DemoActivity";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gps_test);

	}

	public void onRequestLocation(View view) {
		switch (view.getId()) {
		case R.id.gpsBtn:
			Log.d(TAG, "GPS button is clicked");
			requestGPSLocation();
			break;
		case R.id.telBtn:
			Log.d(TAG, "CellID button is clicked");
			requestTelLocation();
			break;
		case R.id.wifiBtn:
			Log.d(TAG, "WI-FI button is clicked");
			requestWIFILocation();
			break;
		case R.id.netBtn:
			Log.d(TAG, "Network button is clicked");
			requestNetworkLocation();
			break;
		}
	}

	private void requestTelLocation() {
		TelephonyManager mTelMan = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		// MCC+MNC. Unreliable on CDMA networks
		String operator = mTelMan.getNetworkOperator();
		String mcc = operator.substring(0, 3);
		String mnc = operator.substring(3);

		GsmCellLocation location = (GsmCellLocation) mTelMan.getCellLocation();
		int cid = location.getCid();
		int lac = location.getLac();
		Log.i(TAG, "requestTelLocation##" + " cid =" + cid + " lac=" + lac);
		JSONObject tower = new JSONObject();
		try {
			tower.put("cell_id", cid);
			tower.put("location_area_code", lac);
			tower.put("mobile_country_code", mcc);
			tower.put("mobile_network_code", mnc);
		} catch (JSONException e) {
			Log.e(TAG, "call JSONObject's put failed", e);
		}

		JSONArray array = new JSONArray();
		array.put(tower);

		List<NeighboringCellInfo> list = mTelMan.getNeighboringCellInfo();
		Iterator<NeighboringCellInfo> iter = list.iterator();
		NeighboringCellInfo cellInfo;
		JSONObject tempTower;
		while (iter.hasNext()) {
			cellInfo = iter.next();
			tempTower = new JSONObject();
			try {
				tempTower.put("cell_id", cellInfo.getCid());
				tempTower.put("location_area_code", cellInfo.getLac());
				tempTower.put("mobile_country_code", mcc);
				tempTower.put("mobile_network_code", mnc);
			} catch (JSONException e) {
				Log.e(TAG, "call JSONObject's put failed", e);
			}
			array.put(tempTower);
		}

		JSONObject object = createJSONObject("cell_towers", array);
		requestLocation(object);
	}

	private void requestWIFILocation() {
		WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifiMan.getConnectionInfo();
		String mac = info.getMacAddress();
		String ssid = info.getSSID();

		JSONObject wifi = new JSONObject();
		try {
			wifi.put("mac_address", mac);
			wifi.put("ssid", ssid);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		JSONArray array = new JSONArray();
		array.put(wifi);

		JSONObject object = createJSONObject("wifi_towers", array);
		requestLocation(object);
	}

	private void requestLocation(JSONObject object) {
		Log.d(TAG, "requestLocation: " + object.toString());
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://www.google.com/loc/json");
		try {
			StringEntity entity = new StringEntity(object.toString());
			post.setEntity(entity);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		try {
			HttpResponse resp = client.execute(post);
			HttpEntity entity = resp.getEntity();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					entity.getContent()));
			StringBuffer buffer = new StringBuffer();
			String result = br.readLine();
			while (result != null) {
				buffer.append(result);
				result = br.readLine();
			}

			Log.d(TAG, buffer.toString());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private JSONObject createJSONObject(String arrayName, JSONArray array) {
		JSONObject object = new JSONObject();
		try {
			object.put("version", "1.1.0");
			object.put("host", "maps.google.com");
			object.put(arrayName, array);
		} catch (JSONException e) {
			Log.e(TAG, "call JSONObject's put failed", e);
		}
		return object;
	}

	private void requestGPSLocation() {

		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				1000 * 60, 100, mLocLis);
	}

	private void requestNetworkLocation() {
		String provider = LocationManager.NETWORK_PROVIDER;
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// locationManager.setTestProviderEnabled("gps", true); //打开
		// 获取位置，如果没有上次的位置信息，则location为 空，所以还要设置监听。
		Location location = locationManager.getLastKnownLocation(provider);
		if (location == null) {
			Log.i(TAG, "location = null");
		} else {
			Log.i(TAG, location.getLatitude() + " " + location.getAltitude());
		}
		// Log.i(TAG, " " + location == null ? "null": location.getLatitude() +
		// " " + location.getAltitude());
		// 60S，100米？ 每隔60S会监听到当前的位置，如果有移动100米，也会监听到位置。
		locationManager.requestLocationUpdates(provider, 1000 * 6, 1000,
				mLocLis);
	}

	private LocationListener mLocLis = new LocationListener() {

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			Log.d(TAG, "onStatusChanged, provider = " + provider);
		}

		@Override
		public void onProviderEnabled(String provider) {
			Log.d(TAG, "onProviderEnabled, provider = " + provider);
		}

		@Override
		public void onProviderDisabled(String provider) {// Gps is not open
			Log.d(TAG, "onProviderDisabled, provider = " + provider);
		}

		@Override
		public void onLocationChanged(Location location) {
			double latitude = location.getLatitude();
			double longitude = location.getLongitude();
			Log.d(TAG, "latitude: " + latitude + ", longitude: " + longitude);
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if (mLocLis != null) {

			mLocMan.removeUpdates(mLocLis);
			mLocLis = null;
		}
	};
}
